<template>
	<view class="content-box">
		<!-- 头部navbar -->
		<navbar :fixed="true" :bgColor="'#fff'" :title="t('withdraw.sqtx')" :leftIcon="true"></navbar>
		
		<!-- 提现地址 -->
		<view class="form-section">
			<text class="label">{{ t('withdraw.txdz') }}</text>
			<view class="input-wrapper" :class="{ 'focused': addressFocused }">
				<input 
					type="text" 
					class="input" 
					:placeholder="t('withdraw.qsrtxdz')" 
					v-model="address" 
					@focus="addressFocused = true" 
					@blur="addressFocused = false"
				/>
			</view>
		</view>
		
		<!-- 确认地址 -->
		<view class="form-section">
			<text class="label">{{ t('withdraw.qrdz') }}</text>
			<view class="input-wrapper" :class="{ 'focused': confirmAddressFocused }">
				<input 
					type="text" 
					class="input" 
					:placeholder="t('withdraw.qsrtxdz')" 
					v-model="confirmAddress" 
					@focus="confirmAddressFocused = true" 
					@blur="confirmAddressFocused = false"
				/>
			</view>
		</view>
		
		<!-- 资金密码 -->
		<view class="form-section">
			<text class="label">资金密码:</text>
			<view class="input-wrapper" :class="{ 'focused': payPasswordFocused }">
				<input 
					type="password" 
					class="input" 
					placeholder="输入资金密码" 
					v-model="payPassword" 
					@focus="payPasswordFocused = true" 
					@blur="payPasswordFocused = false"
					maxlength="6"
				/>
			</view>
		</view>
		
		<!-- 使用已定义地址 -->
		<view class="form-section address-form">
			<text class="label">{{ t('withdraw.sydydz') }}</text>
			<view class="address-options">
				<view 
					v-for="(item, index) in predefinedAddresses" 
					:key="index" 
					class="address-option" 
					:class="{ 'selected': selectedAddressIndex === index }"
					@click="selectAddress(index)"
				>
					<text>{{ item.name }}</text>
				</view>
				<view class="address-option add-option">
					<image src="/static/icon/add.svg" class="add-icon"></image>
				</view>
			</view>
		</view>
		
		<!-- 确认按钮 -->
		<view class="action-button btn-primary" @click="submit">
			<text>{{ t('withdraw.qr') }}</text>
		</view>
		<GlobalPopup ref="popup"></GlobalPopup>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import { useI18n } from 'vue-i18n';
	import { withdrawApi, walletAddressApi } from '@/utils/api.js';
	const { t, locale } = useI18n();
	const popup = ref()
	
	// 提现金额（从上一页传递）
	const withdrawAmount = ref(0);
	
	// 地址输入状态
	const address = ref('');
	const confirmAddress = ref('');
	const addressFocused = ref(false);
	const confirmAddressFocused = ref(false);
	
	// 资金密码输入状态
	const payPassword = ref('');
	const payPasswordFocused = ref(false);
	
	// 预定义地址
	const predefinedAddresses = ref([]);
	const selectedAddressIndex = ref(-1);
	const loading = ref(false);
	
	// 获取钱包地址列表
	const getWalletAddresses = async () => {
		try {
			loading.value = true;
			const response = await walletAddressApi.getPage({
				pageNo: 1,
				pageSize: 20
			});
			
			if (response && response.code === 0 && response.data && response.data.list) {
				predefinedAddresses.value = response.data.list.map(item => ({
					id: item.id,
					name: item.name || item.address.substring(0, 8) + '...',
					address: item.address
				}));
			}
		} catch (error) {
			console.error('获取钱包地址失败:', error);
			// 如果接口失败，使用默认地址
			predefinedAddresses.value = [
				{ name: t('withdraw.wmm'), address: 'TW4V7n2MFENVm6tNvbDUvsygC5L2YdtsZu' },
				{ name: t('withdraw.qb1'), address: 'TW4V7n2MFENVm6tNvbDUvsygC5L2YdtsZu' }
			];
		} finally {
			loading.value = false;
		}
	};

	// 选择预定义地址
	const selectAddress = (index) => {
		if (selectedAddressIndex.value === index) {
			// 取消选择
			selectedAddressIndex.value = -1;
			address.value = '';
			confirmAddress.value = '';
		} else {
			// 选择地址
			selectedAddressIndex.value = index;
			const selectedAddress = predefinedAddresses.value[index].address;
			address.value = selectedAddress;
			confirmAddress.value = selectedAddress;
		}
	};
	// 验证地址输入
	const validateAddress = () => {
		if (!address.value.trim()) {
			uni.showToast({
				title: '请输入提现地址',
				icon: 'none'
			});
			return false;
		}
		
		if (!confirmAddress.value.trim()) {
			uni.showToast({
				title: '请确认提现地址',
				icon: 'none'
			});
			return false;
		}
		
		if (address.value !== confirmAddress.value) {
			uni.showToast({
				title: '两次输入的地址不一致',
				icon: 'none'
			});
			return false;
		}
		
		return true;
	};
	
	// 验证资金密码
	const validatePayPassword = () => {
		if (!payPassword.value.trim()) {
			uni.showToast({
				title: '请输入资金密码',
				icon: 'none'
			});
			return false;
		}
		
		if (payPassword.value.length !== 6) {
			uni.showToast({
				title: '资金密码必须为6位数字',
				icon: 'none'
			});
			return false;
		}
		
		return true;
	};
	
	// 提交提现申请
	const submit = async () => {
		if (!validateAddress()) {
			return;
		}
		
		if (!validatePayPassword()) {
			return;
		}
		
		try {
			// 显示加载状态
			uni.showLoading({
				title: '提交中...'
			});
			
			// 调用提现申请接口
			const response = await withdrawApi.create({
				withAmount: withdrawAmount.value,
				withAddress: address.value,
				payPassword: payPassword.value
			});
			
			uni.hideLoading();
			
			if (response && response.code === 0) {
				// 提现申请成功
				popup.value.open({
					title: t('withdraw.ytjsh'),
					content: t('withdraw.qnxdd'),
					loading: false,
					success: true
				});
				
				// 延迟跳转回首页
				setTimeout(() => {
					uni.navigateBack({
						delta: 2 // 返回到首页
					});
				}, 2000);
			} else {
				// 提现申请失败
				uni.showToast({
					title: response.msg || '提现申请失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();
			console.error('提现申请失败:', error);
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		}
	};
	
	// 获取页面参数和初始化数据
	onMounted(async () => {
		// 获取页面参数
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.options;
		
		if (options.amount) {
			withdrawAmount.value = parseFloat(options.amount);
		}
		
		// 获取钱包地址列表
		await getWalletAddresses();
	});
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding: 43.55rpx 41.81rpx 100rpx;
		box-sizing: border-box;
	}
	
	.form-section {
		margin-top: 27.87rpx;
	}
	
	.label {
		font-size: 31.4rpx;
		font-weight: 400;
		color: #333;
		margin-bottom: 13.94rpx;
		display: block;
	}
	
	.input-wrapper {
		border-radius: 27.91rpx;
		background: #F9FAFB;
		border: 1.74rpx solid #DBDBDB;
		transition: all 0.3s;
		height: 97.67rpx;
		padding:0 66.2rpx;
		display: flex;
		align-items: center;
		&.focused {
			border: 1px solid transparent;
			background: linear-gradient(#F9FAFB, #F9FAFB) padding-box,
						linear-gradient(90deg, #0CB394 0%, #058FC8 100%) border-box;
		}
		
		.input {
			width: 100%;
			font-size: 24.42rpx;
			font-weight: 400;
			color: #333;
		}
	}
	.address-form{
		margin-top: 156.79rpx;
		.label{
			font-size: 27.91rpx;
			font-weight: 400;
		}
	}
	.address-options {
		display: flex;
		flex-wrap: wrap;
		gap: 20.93rpx;
		margin-top: 20.93rpx;
	}
	
	.address-option {
		background-color: #FFFFFF;
		border-radius: 34.88rpx;
		width: 130.81rpx;
		height: 69.77rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24.42rpx;
		font-weight: 500;
		color: #141416;
		border: 2rpx solid transparent;
		&.selected {
			border: 2rpx solid #3B82F6;
		}
		
		&.add-option {
			background-color: transparent;
			border: 1px dashed #999;
			width: 69.77rpx;
			height: 69.77rpx;
			opacity: 1;
			border: 1.74rpx dashed #333333;;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			box-sizing: border-box;
			margin: 0 28.16rpx;
		}
		
		.add-icon {
			width: 24.4rpx;
			height: 24.4rpx;
		}
	}
	
	.action-button {
		width: 570.35rpx;
		height: 97.67rpx;
		border-radius: 26.16rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #FFFFFF;
		font-size: 32rpx;
		font-weight: 500;
		margin: 60rpx auto 0;
		position: fixed;
		bottom: 69.69rpx;
		left: 88.85rpx;
	}
</style>